#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description:       :
@Date     :2021/03/25 21:29:02
@Author      :chenqi
@version      :1.0
'''
from shapely.geometry import Polygon
import numpy as np


def convert_polygon(rectangle: np) -> Polygon:
    polygon = Polygon(rectangle).convex_hull
    return polygon


def get_intersection(poly1: Polygon, poly2: Polygon) -> float:
    inter_area = poly1.intersection(poly2).area
    return inter_area


def get_union(poly1: Polygon, poly2: Polygon) -> float:
    return poly1.area + poly2.area


def get_IOU(rect1: np.array, rect2: np.array):
    poly1 = convert_polygon(rect1)
    poly2 = convert_polygon(rect2)
    area_intersection = get_intersection(poly1, poly2)
    area_union = get_union(poly1, poly2)-area_intersection
    return area_intersection/area_union


if __name__ == '__main__':
    rect1 = np.array([0, 0, 2, 0, 0, 2, 2, 2], dtype=float).reshape(4, 2)
    rect2 = np.array([-1, 2, 1, 3, 3, 2, 1, 1], dtype=float).reshape(4, 2)
    iou = get_IOU(rect1, rect2)
    print(iou)
